<template>
  <div class="pullup">
    <div ref="scroll" class="pullup-wrapper">
      <div class="pullup-content">
        <ul class="pullup-list">
          <li v-for="i of data" :key="i" class="pullup-list-item">
            {{ i % 5 === 0 ? "scroll up 👆🏻" : `I am item ${i} ` }}
          </li>
        </ul>
        <div class="pullup-tips">
          <div v-if="!isPullUpLoad" class="before-trigger">
            <span class="pullup-txt">Pull up and load more</span>
          </div>
          <div v-else class="after-trigger">
            <span class="pullup-txt">Loading...</span>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script>
import BScroll from "@better-scroll/core";
import ScrollBar from "@better-scroll/scroll-bar";
import MouseWheel from "@better-scroll/mouse-wheel";
import Pullup from "@better-scroll/pull-up";

BScroll.use(ScrollBar);
BScroll.use(MouseWheel);
BScroll.use(Pullup);

export default {
  data() {
    return {
      isPullUpLoad: false,
      data: 20,
    };
  },
  mounted() {
    this.initBscroll();
  },
  beforeDestroy() {
    this.bscroll.destroy();
  },
  methods: {
    initBscroll() {
      this.bscroll = new BScroll(this.$refs.scroll, {
        probeType: 3,
        scrollX: false,
        scrollY: true,
        mouseWheel:true,
        scrollbar: {
          fade: true,
          minSize: 3,
        },
        pullUpLoad: true,
      });
      this.bscroll.on("pullingUp", this.pullingUpHandler);
    },
    async pullingUpHandler() {
      console.log("上拉加载更多内容");
      this.isPullUpLoad = true;
      await this.requestData();
      this.bscroll.finishPullUp();
      this.bscroll.refresh();
      this.isPullUpLoad = false;
    },
    async requestData() {
      try {
        const newData = await this.ajaxGet();
        this.data += newData;
      } catch (err) {
        console.log(err);
      }
    },
    ajaxGet(/* url */) {
      return new Promise((resolve) => {
        setTimeout(() => {
          resolve(20);
        }, 1000);
      });
    },
  },
};
</script>

<style lang="scss" scoped>
.pullup {
  position: absolute;
  top: 60px;
  left: 0;
  right: 0;
  bottom: 0;
  .pullup-wrapper {
    height: 100%;
    padding: 0 10px;
    overflow: hidden;
    .pullup-list {
      .pullup-list-item {
        padding: 10px 0;
        border-bottom: 1px solid #dedede;
      }
    }
    .pullup-tips {
      padding: 20px;
      text-align: center;
      color: #999;
    }
  }
}
</style>